package com.dao.impl;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import com.dao.TeacherDAO;
import com.dto.TeacherDTO;
import com.util.db.DBUtil;

public class TeacherDAOImpl implements TeacherDAO {
	private Connection conn;

	public TeacherDAOImpl() {
		conn = DBUtil.getConnection();
	}

	@Override
	public TeacherDTO findTeacherByName(String username) {
		TeacherDTO teacherDTO = null;
		String sql = "SELECT * FROM teacher WHERE user_name=?;";
		QueryRunner qr = new QueryRunner();

		try {
			teacherDTO = qr.query(conn, sql, new BeanHandler<TeacherDTO>(
					TeacherDTO.class), username);
		} catch (SQLException e) {
			return null;
		} finally {
			try {
				DbUtils.close(conn);
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return teacherDTO;
	}

	@Override
	public boolean findTeacher(String username, String password) {
		boolean result = false;

		TeacherDTO teacherDTO = getTeacher(username, password);

		result = (teacherDTO != null) ? true : false;
		return result;
	}

	@Override
	public TeacherDTO getTeacher(String username, String password) {
		TeacherDTO teacherDTO = null;
		String sql = "SELECT * FROM teacher WHERE user_name=? AND password=?;";
		QueryRunner qr = new QueryRunner();

		try {
			teacherDTO = qr.query(conn, sql, new BeanHandler<TeacherDTO>(
					TeacherDTO.class), username, password);
		} catch (SQLException e) {
			return null;
		} finally {
			try {
				DbUtils.close(conn);
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return teacherDTO;
	}

	@Override
	public List<TeacherDTO> getTeachers() {
		List<TeacherDTO> teachers = null;
		String sql = "SELECT * FROM teacher;";
		QueryRunner qr = new QueryRunner();

		try {
			teachers = qr.query(conn, sql, new BeanListHandler<TeacherDTO>(
					TeacherDTO.class));
		} catch (SQLException e) {
			return null;
		} finally {
			try {
				DbUtils.close(conn);
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return teachers;
	}

	@Override
	public TeacherDTO getTeacherById(String teacher_id) {
		TeacherDTO teacherDTO = null;
		String sql = "SELECT * FROM teacher WHERE t_id=?;";
		QueryRunner qr = new QueryRunner();

		try {
			teacherDTO = qr.query(conn, sql, new BeanHandler<TeacherDTO>(
					TeacherDTO.class), teacher_id);
		} catch (SQLException e) {
			return null;
		} finally {
			try {
				DbUtils.close(conn);
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return teacherDTO;
	}

}
